package distributed.controller;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import distributed.entity.Event;
import distributed.entity.EventModel;
import distributed.entity.User;

import server.ClientState;
import xml.Message;

/**
 * Controller to handle the generation of an event from a given xml Nodeset
 * @author Sam Jaffe, Marcus Menghini
 *
 */
public class CreateEventController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		//Get the base node
		Node base = request.contents.getFirstChild();
		//Get its children
		NodeList nl = base.getChildNodes();
		//Get the attributes of the request
		NamedNodeMap map = base.getAttributes();
		
		//Get all of the attribute data
		boolean isOpen = map.getNamedItem("type").getNodeValue().equals("open");
		String question = map.getNamedItem("question").getNodeValue();
		int numChoices = Integer.decode(map.getNamedItem("numChoices").getNodeValue());
		int numRounds = Integer.decode(map.getNamedItem("numRounds").getNodeValue());
		
		//Make the event
		String eventID = EventModel.getInstance().
						createEvent(numChoices, numRounds, question, isOpen);
		Event event = EventModel.getInstance().getEvent(eventID); //Retrieve it
		
		//Iterate through the map and add all of the choices
		for (int i = 0; i < nl.getLength()-1; i++) {
			NamedNodeMap tempMap = nl.item(i).getAttributes();
			//Get the data from the item
			int position = Integer.decode(tempMap.getNamedItem("index").getNodeValue());
			String choice = tempMap.getNamedItem("value").getNodeValue();
			event.setChoice(position, choice); //Set it as a choice
		}
		//Get our user
		String userName = nl.item(nl.getLength()-1).getAttributes().
							getNamedItem("name").getNodeValue();
		//Log him in (just in case)
		event.signIn(new User(userName, state.id(), event.next(state.id())));
		//Make sure the event wasn't started
		event.unStart();
		//Store the event in the db
		DataBaseController.getInstance().storeEvent(event, eventID);
		
		//Its an Easter Egg
		if (question.contains("movie"))
			xmlString = "<response id = '" + request.id() + 
						"' success='true' reason='You should watch Waterworld'>"
						+ "<createResponse id='" + eventID + "'/></response>";
		else
			xmlString = Message.responseHeader(request.id()) + 
			"<createResponse id='" + eventID
				+ "'/></response>";
		//Send back our response
		return new Message(xmlString);
	}

	/**
	 * @return CreateEventController
	 */
	public IProtocolController newCopy() {
		return new CreateEventController();
	}

}
